import {
  ConfirmModel
} from "../../models/confirm";
import {
  PayModel
} from '../../models/pay'
import {
  Format
} from '../../utils/common'
import {
  Common
}
from "../../utils/common";
import {
  RechargeModel
} from '../../models/recharge';
const app = getApp();
const confirmModel = new ConfirmModel()
const payModel = new PayModel()
const rechargeModel = new RechargeModel()
const format = new Format()
const common = new Common()
let last
let onTheWay = {}
let firstShowOilAndGun = true
Page({
  data: {
    showTop: false,
    btnDisabled: true,
    inputDisabled: true, //选择油枪
    currentQuickIndex: null,
    payAmountInput: '',
    payDiscount: 0,
    payAmount: 0,
    realAmount: 0,
    quickAmount: [{
        price: 100,
      }, {
        price: 200,
      },
      {
        price: 300,
      }
    ],
    tabs: [],
    activeTab: 0,
    oilGunList: [],
    showTicket: false,
    canUseTicketName: '无可用',
    canUseTicketAmount: 0,
    canUsetickets: [],
    modalOpened: false,
    authCode: '',
    openPop: false,
    radioitems: [
      {name: '花呗分期', value: 6, checked: false, icon: '/assets/payIcon4.jpg',arrowType: 'circle'},
      {name: '支付宝', value: 1, checked: true, icon: '/assets/payIcon2.jpg',arrowType: 'success-o'},
      {name: '壳牌会员卡', value: 3, icon: '/assets/payIcon3.jpg',arrowType: 'circle'}
    ],
    payTypeIndex: 1,
    tradeType: 1,
    showActiveBar: false,
    pointMsg: '',
    huabeiIndex: 0, //花呗分期默认选中
    huabei: [], // 花呗list
    taxRate: [0.023,0.045,0.075],
    modalOpened4: false,
    MainActive: '', // 运营活动弹窗链接及内容
  },
  onLoad(options) {
    console.log('onLoad' + JSON.stringify(options))
    this.setData({
      'options': JSON.stringify(app.globalData.onLaunch),
    })
    // app.editTabBar();
    if (options && options.entityNum) {
      this.setData({
        'entityNum': options.entityNum,
      })
    } else {
      this.setData({
        'entityNum': app.globalData.entityNum,
      })
    }
    const station = app.globalData.station
    if (station){
      const shopId = station.alipay_store_id
      const oilNum = station.oil_num
      this.setData({
        'station[shopId]': shopId,
        'station[oilNum]': oilNum,
        'station[jiayouSource]': station.myjy_source
      })
      this.loadStation(shopId, oilNum)
      app.myLogin().then(r => {
        wx.hideLoading();
        this.setData({
          userId: r.id
        })
        this.setData({
          userPhone: r.phone
        })
      })
    }
    // this.getMainActiveParam()

  },
  onChange(extendParams) {
      const { hb_fq_num, hb_fq_seller_percent } = extendParams
      console.log(hb_fq_num, hb_fq_seller_percent);
      // ...
      // https://docs.alipay.com/mini/introduce/pay
    },
    onToggleAvailableAmt(isVisible) {
      console.log(isVisible);
    },
  onShow: function (options) {
    console.log('onShow' + JSON.stringify(options))
    firstShowOilAndGun = true
    const station = app.globalData.station
    console.log(JSON.stringify(station)  + '11111111111111')
    if (!station) {
      // app.getLocation().then(r => {
      //   console.log(JSON.stringify(app.globalData)  + 'app.globalData.station')
      //   const  station = app.globalData.station
      //   const shopId = station.alipay_store_id
      //   const oilNum = station.oil_num
      //   this.setData({
      //     'station[shopId]': shopId,
      //     'station[oilNum]': oilNum,
      //     'station[jiayouSource]': station.myjy_source,
      //   })
      //   this.loadStation(shopId, oilNum)
      //   this.getSlogan()
      //   // this.getUserToExpiredPoint()
      //   app.myLogin().then(r => {
      //     wx.hideLoading();
      //     this.setData({
      //       userId: r.id
      //     })
      //     this.setData({
      //       userPhone: r.phone
      //     })
      //     console.log('r.phone' + r.phone)
      //   })
      // })
    } else {
      this.getSlogan()
      // this.getUserToExpiredPoint()
    }
  },
  // 获取活动
  getSlogan() {
    console.log(app.globalData.station.alipay_store_id)
    confirmModel.getSlogan(app.globalData.station.alipay_store_id).then(res => {
      console.log(res)
      if (res && res.hasSlogan) {
        this.setData({
          'showActiveBar': true,
          activeBarName: res.slogan,
        })
        app.globalData.activeBarphotoUrl = res.photoUrl
      } else {
        this.setData({
          'showActiveBar': false,
        })
      }
    })
  },
  // 获取弹屏活动
  getMainActiveParam() {
    confirmModel.getMainActiveParam(1).then(res => {
      if (res) {
        if (res.imageSrc) {
          if (res.linkSrc) {
            this.setData({
              modalOpened4: true,
              "MainActive[linkSrc]": res.linkSrc,
              "MainActive[imageSrc]": res.imageSrc,
              "MainActive[height]": res.height
            })
          } else {
            this.setData({
              "MainActive[imageSrc]": res.imageSrc,
              "MainActive[height]": res.height,
              modalOpened4: true
            })
          }
        }
      }
    })
  },
  // 关掉弹屏活动
  onModalClick4() {
    this.setData({
      modalOpened4: false,
    });
  },
  // 获取过期积分
  getUserToExpiredPoint() {
    confirmModel.getUserToExpiredPoint().then(res => {
      console.log(res)
      if (res && res.code) {
        if (res.code == '00' && res.expiredPoints != 0 && res.msg) {
          this.setData({
            'pointMsg': res.msg
          })
        } else {
          this.setData({
            'pointMsg': '',
          })
        }
      } else {
        wx.showToast({
          type: 'none',
          content: '查询积分过期失败',
          duration: 1000,
        });
        this.setData({
          'pointMsg': '',
        })
      }
    })
  },
  onOptionMenuClick() {
  },
  loadStation(shopId, oilNum) {
    confirmModel.getStationMsg(shopId, oilNum).then(res => {
      console.log(res)
      if (res) {
        this.setData({
          'station.fullName': res.name,
          'station.name': res.name,
          'station.address': res.address,
          'station.currentPrice': res.price ? format.amount(res.price) : '暂无',
          'station.priceHidden': res.priceHidden?res.priceHidden: false
        })
      }
    })
  },
  loadOilAndGun(shopId) {
    confirmModel.getOilAngGun(shopId).then(res => {
      if (res) {
        this.setData({
          goodsList: res.goodsList
        })
        this.getOilNum(res.goodsList)
      }
    })
  },
  onCounterPlusOne() {
    this.setData({
        openPop: false,
    })
    const shopId = this.data.station.shopId
    firstShowOilAndGun = false
    this.loadOilAndGun(shopId)
    this.setData({
      showTop: true,
    })
  },
  showOilAndGun() {
    // this.getCouponListByOrderId()
    // return
    let vm = this
    console.log(app.globalData.entityNum + 'app.globalData.entityNum')
    if (this.data.entityNum) {
      var entityNum = this.data.entityNum
    } else {
      var entityNum = ''
    }
    if (app.globalData.user) {
      if (app.globalData.user.phone) {
        app.myoilLogin('',entityNum).then(res => {
          wx.hideLoading();
          console.log('myoilLogin------' + JSON.stringify(res))
          if (res.result == 500) {
            wx.showToast({
              type: 'none',
              content: res.message,
              duration: 1000,
            });
            return
          }
          const shopId = this.data.station.shopId
          firstShowOilAndGun = false
          this.loadOilAndGun(shopId)
          this.setData({
            showTop: true,
          })
        })
        return
      }
      wx.getPhoneNumber({
          success: (res) => {
              let encryptedData = res.response;
              app.myoilLogin(encryptedData,entityNum).then(res => {
                wx.hideLoading();
                console.log('myoilLogin------' + JSON.stringify(res))
                if (res.result == 500) {
                  wx.showToast({
                    type: 'none',
                    content: res.message,
                    duration: 1000,
                  });
                  return
                }
                if (res.data.phoneNum) {
                    vm.getCouponListByOrderId()
                }
              })
          },
          fail: (res) => {
              console.log(res);
              console.log('getPhoneNumber_fail');
              wx.showToast({
                type: 'none',
                content: 'getPhoneNumber~失败',
                duration: 1000,
              });
          },
      });
    }
  },
  // 获取注册优惠
  getCouponListByOrderId() {
    let vm = this
    rechargeModel.getCouponListByOrderId().then(res => {
      if (res.activeName || res.src) {
        // res.data=[{'123': '123'},{'123': '123'},{'123': '123'}]
        vm.setData({
          Registeractive: res,
        });
        console.log('123')
        vm.setData({
          openPop: true,
        })
      }
      console.log(res)
    })
  },
  getOilNum(goodsList) {
    const tabs = []
    const oilNum = this.data.station.oilNum
    let activeTab = null
    console.log('油品号为~~~~~~~~~~~~~~~~~~·')
    console.log(goodsList)
    if (goodsList) {
      goodsList.map((v, i) => {
        const m = {}
        m.title = v.oilCode + "#"
        m.price = v.price
        m.id = v.id
        tabs.push(m)
        if (m.title == oilNum) {
          activeTab = i
          onTheWay = {
            title: m.title,
            price: v.price,
            id: v.id
          }
          return
        }
      })
      if (!activeTab) {
        activeTab = 0
          onTheWay = {
            title: goodsList[0].oilCode + "#",
            price: goodsList[0].price,
            id: goodsList[0].id
          }
      }
      this.getGunNum(activeTab)
      this.setData({
        tabs,
        activeTab
      })
    }
    
  },
  getGunNum(index) {
    if (this.data.goodsList.length>0) {
      const oilGunList = this.data.goodsList[index].oilGunList
      this.setData({
        oilGunList
      })
    }
  },
  onPopupClose() {
    this.setData({
      showTop: false,
    });
  },

  handleTabClick({
    index
  }) {
    this.tabChange(index)
  },
  handleTabChange({
    index
  }) {
    this.tabChange(index)
  },
  tabChange(index) {
    this.getGunNum(index)
    const v = this.data.tabs[index]
    this.setData({
      activeTab: index,
    });
    onTheWay = {
      title: v.title,
      price: v.price,
      id: v.id
    }
  },
  onItemClick(ev) {
    console.log(ev)
    console.log(this.data.payAmountInput)
    console.log('ev')
    const d = ev.detail
    this.setData({
      'station.gunNum': d.gunNum,
      'station.oilGunId': d.id,
      'station.oilNum': onTheWay.title,
      'station.currentPrice': format.amount(onTheWay.price),
      'station.goodsId': onTheWay.id,
      inputDisabled: false,
      showTop: false
    })
    if (this.data.payAmountInput) {
    }
  },

  changePayAmount(e) {
    if (this.data.inputDisabled) {
      this.tip()
      return
    }
    const currentQuickIndex = e.currentTarget.dataset.index
    const currentPayInput = this.data.quickAmount[currentQuickIndex]
    let taxRate = this.data.taxRate
    if (this.data.tradeType == 6) {
      this.setData({
        huabeiIndex: 0,
        'huabei': [{serviceCharge: parseInt(currentPayInput.price*100*taxRate[0]/3),taxRate: taxRate[0],number: 3,periodCost: parseInt(currentPayInput.price*100/3) + parseInt(currentPayInput.price*100*taxRate[0]/3)},
                  {serviceCharge: parseInt(currentPayInput.price*100*taxRate[1]/6),taxRate: taxRate[1],number: 6,periodCost: parseInt(currentPayInput.price*100/6)+parseInt(currentPayInput.price*100*taxRate[1]/6)},
                  {serviceCharge: parseInt(currentPayInput.price*100*taxRate[2]/12),taxRate: taxRate[2],number: 12,periodCost: parseInt(currentPayInput.price*100/12) +parseInt(currentPayInput.price*100*taxRate[2]/12)}],
        'selectHuabei' : {serviceCharge: parseInt(currentPayInput.price*100*taxRate[0]/3),taxRate: taxRate[0],number: 3,periodCost: parseInt(currentPayInput.price*100/3) + parseInt(currentPayInput.price*100*taxRate[0]/3)}
      })
    }
    
    this.setData({
      currentQuickIndex,
      payAmountInput: currentPayInput.price,
      realAmount: format.amount(currentPayInput.price * 100),
      btnDisabled: false
    })
  },
  onInput(e) {
    last = e.timeStamp
    var mesValue
    if (/^\d{1,5}(\.\d{0,2})?$/.test(e.detail.value)) {
      //满足条件
      mesValue = e.detail.value;
    } else {
      //不满足条件
      mesValue = e.detail.value.substring(0, e.detail.value.length - 1);
      wx.showToast({
        type: 'none',
        content: '支付金额仅支持小数点前5位，小数点后2位',
        duration: 600,
      });
    }
    
    this.setData({
      payAmountInput: mesValue
    })
  
    setTimeout(() => {
      if (last - e.timeStamp == 0) {
        this.countAmount(mesValue)
      }
    }, 300);
  },
  onFocus(e) {
    this.setData({
        'huabeiIndex': 0,
        'payTypeIndex': 1,
        'tradeType': 1
    })
  },
  onConfirm(e) {
    const value = this.data.payAmountInput
    this.countAmount(value)
  },
  countAmount(value) {
    this.setData({
      currentQuickIndex: null,
      payAmountInput: value,
      realAmount: format.amount(value * 100), //显示的总金额
    })
    if (value) {
      this.setData({
        btnDisabled: false
      })
    } else {
      this.setData({
        btnDisabled: true
      })
    }
  },
  // 确定
  getCanUseTicketNew() {
    const d = this.data
    const s = d.station
    const amount = (d.payAmountInput * 100).toFixed(0)
    if (amount <= 0) {
      wx.showToast({
        type: 'none',
        content: '支付金额必须大于0元',
        duration: 600,
      });
      return
    }
    if (this.data.entityNum) {
      var entityNum = this.data.entityNum
    } else {
      var entityNum = ''
    }
    console.log(  JSON.stringify(this.data.station) )
    console.log('entityNum' + entityNum)
    if (app.globalData.userLocation && app.globalData.userLocation.userX) {
      this.checkDistance()
    } else {
      this.createTrade()
    }
  },
  // 支付距离校验
  checkDistance() {
    let checkDistance = app.globalData
    confirmModel.checkDistance(checkDistance.userLocation.userX,checkDistance.userLocation.userY,checkDistance.station.stationX,checkDistance.station.stationY).then(res => {
      console.log(res)
      if (res) {
        if (res.canPay == 1) {
          this.createTrade()
        } else {
          
          this.setData({
            modalOpened: true,
          })
        }
      } else {
        wx.showToast({
          type: 'none',
          content: '支付距离校验失败',
          duration: 1000,
        });
      }
    })
  },
  // 创建订单
  createTrade() {
    const amount = (this.data.payAmountInput * 100).toFixed(0)
    if (this.data.entityNum) {
      var entityNum = this.data.entityNum
    } else {
      var entityNum = ''
    }
    this.setData({
      modalOpened: false,
    })
    confirmModel.createTrade(this.data.tradeType,amount,this.data.station.shopId,app.globalData.user.phone,this.data.station.oilGunId,this.data.station.goodsId,'mayijiayou',1 , this.data.station.oilNum,this.data.station.gunNum,entityNum).then(res => {
      console.log(res)
      if (res) {
        this.setData({
          canUsetickets: [],
          orderId:res.orderId,
          canUseTicketName:res.discount ,
          canUseTicketAmount: res.discount,
          volumn: res.volumn,
          promotionsAmount: res.promotionsAmount,
          couponAmount: res.couponAmount,
          realAmount: format.amount((this.data.payAmountInput - res.discount / 100) * 100), //显示的总金额
        })
        this.toPayPop()
      } else {
        wx.showToast({
          type: 'none',
          content: '获取优惠金额失败',
          duration: 1000,
        });
      }
    })
  },
  // 前往确认订单页面
  toPayPop() {
    const d = this.data
    const s = d.station
    if ( !d.orderId) {
      wx.showToast({
        type: 'none',
        content: '创建订单失败，请重试',
        duration: 600,
      });
      return
    }
    console.log(this.data)
    
    let money = (format.amountClear(d.realAmount)).toFixed(0)
    let selectHuabei = ''
    if (this.data.tradeType != 6) {
      this.data.selectHuabei = ''
    } else {
      let taxRate = this.data.selectHuabei.taxRate
      selectHuabei = {
        serviceCharge: parseInt(money*taxRate/this.data.selectHuabei.number),
        periodCost: parseInt(money/this.data.selectHuabei.number) + parseInt(money*taxRate/this.data.selectHuabei.number),
        number: this.data.selectHuabei.number,
      }
    }
    let a = {
      oilNum: this.data.station.oilNum,
      gunNum: this.data.station.gunNum,
      payAmountInput: this.data.payAmountInput,
      canUseTicketAmount: this.data.canUseTicketAmount,
      realAmount1: this.data.realAmount,
      amount: (d.payAmountInput * 100).toFixed(0),
      subject: d.station.fullName,
      jiayouSource: d.station.jiayouSource,
      realAmount: (format.amountClear(d.realAmount)).toFixed(0),
      shopId: s.shopId,
      orderId: d.orderId,
      // oilGunId: s.goodsId,
      oilGunId: s.oilGunId,
      volumn: d.volumn,
      tradeType: this.data.tradeType,
      promotionsAmount: this.data.promotionsAmount,
      couponAmount: this.data.couponAmount,
      selectHuabei: selectHuabei
    }
    wx.navigateTo({
      url: '/pages/confirmOrder/confirmOrder?item=' + JSON.stringify(a)
    })
  },
  // 选择油枪弹窗
  tip() {
    if (this.data.inputDisabled) {
      wx.showToast({
        type: 'none',
        content: '请选择枪号',
        duration: 1000,
      });
      
    }
  },
  // 选择支付方式
  radioChange: function (e) {
      let item = e.currentTarget.dataset
      if (item.item.value == 6) {
        let taxRate = this.data.taxRate
        if (this.data.payAmountInput < 100) {
          wx.showToast({
            type: 'none',
            content: '花呗分期最低消费为100元，请修改您的加油金额',
            duration: 1000,
          });
          return
        }
        let payAmountInput = this.data.payAmountInput
        this.setData({
          'huabei': [{serviceCharge: parseInt(payAmountInput*100*taxRate[0]/3),taxRate: taxRate[0],number: 3,periodCost: parseInt(payAmountInput*100/3) + parseInt(payAmountInput*100*taxRate[0]/3)},
                    {serviceCharge: parseInt(payAmountInput*100*taxRate[1]/6),taxRate: taxRate[1],number: 6,periodCost: parseInt(payAmountInput*100/6)+parseInt(payAmountInput*100*taxRate[1]/6)},
                    {serviceCharge: parseInt(payAmountInput*100*taxRate[2]/12),taxRate: taxRate[2],number: 12,periodCost: parseInt(payAmountInput*100/12) +parseInt(payAmountInput*100*taxRate[2]/12)}],
          'selectHuabei' : {serviceCharge: parseInt(payAmountInput*100*taxRate[0]/3),taxRate: taxRate[0],number: 3,periodCost: parseInt(payAmountInput*100/3) + parseInt(payAmountInput*100*taxRate[0]/3)}
        })
        
      }
      this.setData({
          'payTypeIndex': item.index,
          'tradeType': item.item.value
      })
  },
  //  选择花呗期数
  changehuabei(e) {
    console.log(e)
    let item = e.currentTarget.dataset
    this.setData({
      huabeiIndex: item.index,
      selectHuabei: item.item,
    })

  },
  // 前往油站选择
  goselectOilStation() {
    this.setData({
      modalOpened: false,
    })
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },
  // 前往活动页面
  goactive () {
    wx.navigateTo({
      url: '/pages/active/active'
    })
  },
  // 点击底部按钮
  toPage(e) {
    const url = e.currentTarget.dataset.url
    if (url == 'mainAactive') {
      this.setData({
        modalOpened4: false
      })
      wx.switchTab({
        url: 'pages/recharge/recharge'
      })
      // wx.navigateTo({
      //   url: this.data.MainActive.linkSrc,
      // })
    } else {
      wx.navigateTo({
        url: url,
      })
    }
    
    
  },
  toMayi(){
    app.toMayi()
  }
});